<template>
  <el-container class="center-container">
    <el-card class="info-container">
      <h2>提交假期申请</h2>
      <el-form :model="leaveApplication" ref="leaveForm" label-width="120px">
        <el-form-item label="员工ID">
          <el-input v-model="leaveApplication.employeeId"></el-input>
        </el-form-item>
        <el-form-item label="假期类型">
          <el-select v-model="leaveApplication.leaveType" placeholder="请选择假期类型">
            <el-option label="病假" value="病假"></el-option>
            <el-option label="事假" value="事假"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker v-model="leaveApplication.startDate" type="date" placeholder="选择开始日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker v-model="leaveApplication.endDate" type="date" placeholder="选择结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="原因">
          <el-input type="textarea" v-model="leaveApplication.reason"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitLeaveApplication">提交申请</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-container>
</template>

<script>
export default {
  data() {
    return {
      leaveApplication: {
        employeeId: '',
        leaveType: '',
        startDate: '',
        endDate: '',
        reason: ''
      }
    };
  },
  methods: {
    async submitLeaveApplication() {
      try {
        // 格式化日期为 YYYY-MM-DD
        const formatDate = (date) => {
          const d = new Date(date);
          const year = d.getFullYear();
          const month = String(d.getMonth() + 1).padStart(2, '0');
          const day = String(d.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
        };

        const formattedStartDate = formatDate(this.leaveApplication.startDate);
        const formattedEndDate = formatDate(this.leaveApplication.endDate);

        const response = await this.$axios.post('/api/leave/apply', {
          ...this.leaveApplication,
          startDate: formattedStartDate,
          endDate: formattedEndDate
        });

        if (response.data.status === 'success') {
          this.$message.success('假期申请提交成功');
          this.$refs.leaveForm.resetFields();
        } else {
          this.$message.error(response.data.message);
        }
      } catch (error) {
        console.error('Error submitting leave application:', error);
        this.$message.error('提交申请失败，请重试');
      }
    }
  }
};
</script>

<style scoped>
.center-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
.info-container {
  border: 1px solid #dcdfe6;
  padding: 20px;
  border-radius: 5px;
  background-color: #f9f9f9;
  max-width: 600px;
  width: 100%;
}
.el-table th, .el-table td {
  padding: 8px;
}
</style>
